<script lang="ts">
// 设备分类
export default {
  name: "classifyPage"
};
</script>
<script setup lang="ts">
import { reactive, ref, nextTick, onMounted } from "vue";
import { changeHeight } from "/@/utils/public.mixin";
import { VXETable } from "vxe-table";
import {
  addDeviceType,
  updateDeviceType,
  queryDeviceTypePage,
  deleteDeviceType
} from "/@/api/equipment/classify";
import { successMessage, errorMessage } from "/@/utils/message";
import { ElForm } from "element-plus";
import { useRoute } from "vue-router";
import { loadEnv } from "@build/index";
import { getToken } from "/@/utils/auth";
import { ElLoading } from "element-plus";
const route = useRoute();
const routeName = route.name as string;
// 加载环境变量 VITE_PROXY_DOMAIN（开发环境）  VITE_PROXY_DOMAIN_REAL（打包后的线上环境）
const { VITE_PROXY_DOMAIN, VITE_PROXY_DOMAIN_REAL } = loadEnv();
const actionUrl =
  process.env.NODE_ENV === "production"
    ? VITE_PROXY_DOMAIN_REAL
    : (VITE_PROXY_DOMAIN as string);

const getTo = getToken();
const token = JSON.parse(getTo).accessToken as string;
// 上传文件时的token
const myHeaders = reactive({
  Authorization: token
});
const page = reactive({
  pageNum: 1,
  pageRow: 20,
  totalResult: 0
});
const table = reactive({
  loading: false,
  tableData: [] as any[],
  tableHeight: 0, //表格高度
  listQuery: {
    code: "",
    name: ""
  }
});
const upload = ref();
// 查询
const searchEvent = () => {
  const data: any = {};
  Object.assign(data, table.listQuery);
  dialog.codePlan = table.listQuery.code;
  dialog.namePlan = table.listQuery.name;
  data.pageNum = page.pageNum;
  data.pageRow = page.pageRow;
  table.loading = true;
  queryDeviceTypePage(data).then((res: any) => {
    if (res.code === 0) {
      table.tableData = res.data.list;
      page.totalResult = res.data.total;
    }
    table.loading = false;
  });
};
// 分页发生改变时会触发该事件
const handlePageChange = ({ currentPage, pageSize }) => {
  page.pageNum = currentPage;
  page.pageRow = pageSize;
  searchEvent();
};
const dialog = reactive({
  codePlan: "",
  namePlan: "",
  close: [] as any,
  loading: false,
  submitLoading: false,
  selectRow: null,
  showEdit: false,
  tableData: [] as any[],
  typeData: [] as any[],
  disabledDate: function (time) {
    return time.getTime() - 8.64e7 < Date.now();
  },
  formLabelWidth: "120px",
  insertForm: {
    code: "",
    id: 0,
    mdesc: "",
    name: "",
    productModel: "",
    productSpec: ""
  },
  formRules: {
    name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
    code: [{ required: true, message: "请输入分类编号", trigger: "blur" }],
    // mdesc: [{ required: true, message: "请输入描述"}],
    productModel: [
      { required: true, message: "请输入产品型号", trigger: "blur" }
    ],
    productSpec: [
      { required: true, message: "请输入产品规格", trigger: "blur" }
    ]
  }
});
const insertForm = ref<InstanceType<typeof ElForm>>();
// 新增
const insertEvent = () => {
  dialog.selectRow = null;
  dialog.showEdit = true;
};
// 修改
const editEvent = (row: any) => {
  Object.keys(dialog.insertForm).forEach(key => {
    dialog.insertForm[key] = row[key];
  });
  dialog.selectRow = row;
  dialog.showEdit = true;
};
// 表单提交
const submitEvent = () => {
  insertForm.value.validate(valid => {
    if (valid) {
      dialog.submitLoading = true;
      if (dialog.selectRow) {
        // 修改
        updateDeviceType(dialog.insertForm)
          .then((res: any) => {
            if (res.code === 0) {
              successMessage("操作成功");
              searchEvent();
              handleClose();
            } else {
              errorMessage(res.message);
              dialog.submitLoading = false;
            }
          })
          .catch(() => {
            errorMessage("操作失败");
            dialog.submitLoading = false;
          });
      } else {
        // 新增
        addDeviceType(dialog.insertForm)
          .then((res: any) => {
            if (res.code === 0) {
              successMessage("操作成功");
              searchEvent();
              handleClose();
            } else {
              errorMessage(res.message);
              dialog.submitLoading = false;
            }
          })
          .catch(() => {
            errorMessage("操作失败");
            dialog.submitLoading = false;
          });
      }
    }
  });
};
// 删除分类
const deleteData = async (id: any) => {
  const type = await VXETable.modal.confirm("您确定要删除该数据?");
  if (type === "confirm") {
    deleteDeviceType(id).then((res: any) => {
      if (res.code === 0) {
        searchEvent();
        successMessage("删除成功");
      } else {
        errorMessage(res.message);
      }
    });
  }
};
//下载数据
const upPlan = () => {
  window.open(
    actionUrl +
      `/device-type/downloadDeviceType?code=${dialog.codePlan}&name=${dialog.namePlan}`
  );
};
//下载模板
const upClass = () => {
  window.open(actionUrl + "/device-type/downloadTemplete");
};
//上传设备分类数据
// 文件上传成功
const fileSuccess = () => {
  setTimeout(() => {
    dialog.close.close();
  }, 1000);
  successMessage("上传成功");
  upload.value.clearFiles();
  searchEvent();
};
// 文件上传失败
const fileError = () => {
  errorMessage("上传失败");
};
// 文件上传前
const fileBefore = file => {
  const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
  const whiteList = ["xlsx", "xls"];
  if (whiteList.indexOf(fileSuffix) === -1) {
    errorMessage("传文件只能是xlsx,xls格式");
    return false;
  }
  dialog.close = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)"
  });
  dialog.loading = true;
};

const handleClose = () => {
  nextTick(() => {
    insertForm.value.resetFields();
    dialog.submitLoading = false;
    dialog.showEdit = false;
  });
};
// mounted
onMounted(() => {
  nextTick(() => {
    // 将表格和工具栏进行关联
    searchEvent();
    table.tableHeight = changeHeight();
  });
});
</script>

<template>
  <div>
    <!-- 工具栏 -->
    <vxe-form :data="table.listQuery">
      <vxe-form-item title="分类名称" field="name" :item-render="{}">
        <template #default="{ data }">
          <vxe-input
            v-model="data.name"
            placeholder="请输入分类名称"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="分类编号" field="code" :item-render="{}">
        <template #default="{ data }">
          <vxe-input
            v-model="data.code"
            placeholder="请输入分类编号"
          ></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <vxe-button
            status="primary"
            icon="fa fa-search"
            v-auth="routeName + ':search'"
            @click="searchEvent"
            >查询</vxe-button
          >
          <vxe-button
            icon="fa fa-clone"
            v-auth="routeName + ':U9'"
            status="primary"
            >从U9同步</vxe-button
          >
          <vxe-button
            status="primary"
            icon="fa fa-plus"
            @click="insertEvent"
            v-auth="routeName + ':add'"
            >新增</vxe-button
          >
          <vxe-button
            status="primary"
            icon="fa fa-download"
            @click="upClass"
            v-auth="routeName + ':add'"
            >下载模板</vxe-button
          >
          <vxe-button
            status="primary"
            icon="fa fa-download"
            @click="upPlan"
            v-auth="routeName + ':edit'"
            >下载数据</vxe-button
          >
          <el-upload
            ref="upload"
            class="upload-file"
            :headers="myHeaders"
            :action="actionUrl + '/device-type/upload'"
            v-auth="routeName + ':upload'"
            :limit="1"
            :auto-upload="true"
            :show-file-list="false"
            :on-success="fileSuccess"
            :on-error="fileError"
            :before-upload="fileBefore"
            style="display: contents"
          >
            <vxe-button status="primary" icon="fa fa-upload"
              >上传文件</vxe-button
            >
          </el-upload>
        </template>
      </vxe-form-item>
    </vxe-form>
    <!-- 列表 -->
    <vxe-table
      ref="xTable"
      border
      show-header-overflow
      show-overflow
      :row-config="{ isHover: true }"
      :print-config="{}"
      :export-config="{}"
      :height="table.tableHeight"
      :data="table.tableData"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="name" title="分类名称" min-width="150"></vxe-column>
      <vxe-column field="code" title="分类编号" min-width="100"></vxe-column>
      <vxe-column
        field="productModel"
        title="产品型号"
        min-width="100"
      ></vxe-column>
      <vxe-column
        field="productSpec"
        title="产品规格"
        min-width="100"
      ></vxe-column>
      <vxe-column field="mdesc" title="描述" min-width="200"></vxe-column>
      <vxe-column title="操作" width="160" fixed="right">
        <template #default="{ row }">
          <vxe-button
            type="text"
            icon="fa fa-edit"
            @click="editEvent(row)"
            v-auth="routeName + ':edit'"
            >编辑</vxe-button
          >
          <vxe-button
            type="text"
            icon="fa fa-trash-o"
            v-auth="routeName + ':delete'"
            @click="deleteData(row.id)"
            >删除</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <vxe-pager
      perfect
      @page-change="handlePageChange"
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageRow"
      :total="page.totalResult"
      :page-sizes="[10, 20, 50, 100, 300]"
      :layouts="[
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'FullJump',
        'Total'
      ]"
    >
    </vxe-pager>
    <!-- 表单弹框 -->
    <el-dialog
      v-model="dialog.showEdit"
      :title="dialog.selectRow ? '编辑&保存' : '新增&保存'"
      width="500px"
      top="7vh"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        ref="insertForm"
        :model="dialog.insertForm"
        :rules="dialog.formRules"
        :label-width="dialog.formLabelWidth"
      >
        <el-form-item prop="name" label="分类名称">
          <el-input
            v-model="dialog.insertForm.name"
            placeholder="请输入分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code" label="分类编号">
          <el-input
            v-model="dialog.insertForm.code"
            placeholder="请输入分类编号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="productModel" label="产品型号">
          <el-input
            v-model="dialog.insertForm.productModel"
            placeholder="请输入产品型号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="productSpec" label="产品规格">
          <el-input
            v-model="dialog.insertForm.productSpec"
            placeholder="请输入产品规格"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mdesc" label="描述">
          <el-input
            type="textarea"
            v-model="dialog.insertForm.mdesc"
            placeholder="请输入描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose" size="small">取 消</el-button>
          <el-button
            type="primary"
            size="small"
            @click="submitEvent"
            :disabled="dialog.submitLoading"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style>
.keyword-lighten {
  color: #000;
  background-color: #ffff00;
}
</style>
<style lang="scss" scoped>
.vxe-input + .vxe-button,
.vxe-input + .vxe-button--dropdown,
.vxe-button + .vxe-button,
.vxe-button + .vxe-button--dropdown {
  margin-left: 0;
}

// .vxe-button.type--button:not(.is--round) {
//   border-radius: 0;
// }

.vxe-toolbar.size--medium {
  padding: 10px;
}

.vxe-table--render-default.size--medium {
  margin-top: 12px;
}

.vxe-button.size--medium.type--button {
  margin-left: 1em;
  height: 32px;
}

.text-model {
  &:hover {
    cursor: pointer;
  }
}
:deep(.vxe-modal--wrapper.type--modal .vxe-modal--body),
:deep(.vxe-modal--wrapper.type--modal .vxe-modal--body .vxe-modal--content) {
  overflow: inherit;
}
.el-date-editor.el-input__inner,
.el-form-item :deep(.el-date-editor.el-input),
.el-select {
  width: 100% !important;
}
</style>
